package org.oschina.api.user.user.queue;

import org.oschina.Constants;
import org.oschina.api.user.user.dao.UserDAO;
import org.oschina.api.user.user.model.User;
import org.oschina.helper.messagequeue.IMessageQueueHelper;
import org.oschina.queue.BaseQueue;
import org.oschina.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 用户状态刷新队列
 */
@Component
public class UserStatusRefreshQueue extends BaseQueue {
	
	private final static Logger logger=LoggerFactory.getLogger(UserStatusRefreshQueue.class);

	@Autowired
	private IMessageQueueHelper messageQueueHelper;
	@Autowired
	private UserDAO userDAO;
	
	@Scheduled(fixedDelay=1000)
	private synchronized void handle()
	{
		Integer uid=(Integer) get(Constants.QUEUE_USER_STATUS_REFRESH,Integer.class);
		if(uid==null)
			return;
		
		User user=userDAO.getOnlineCache(uid);
		
		if(!isOnline(user))
		{
			logger.info("ID为 '{}',用户名为'{}' - 已下线",user.getId(),user.getUsername());
			messageQueueHelper.send(Constants.QUEUE_USER_LOGOUT_HANDLE,user);
		}
		else
			messageQueueHelper.send(Constants.QUEUE_USER_STATUS_REFRESH,uid);
	}
	
	/**
	 * 是否在线
	 * @param user
	 * @return
	 */
	private boolean isOnline(User user)
	{
		return (user!=null && user.getLast_post()>=0 && DateUtil.now()-user.getLast_post()<Constants.REFRESH_ONLINE_USER);
	}
}